package com.shaoshaohuo.app.adapter;

import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.ui.LoginActivity;

public class SplashViewPagerAdapter extends PagerAdapter {
	//界面列表  
    private List<View> views;  
    private Activity activity;
    public SplashViewPagerAdapter (List<View> views, Activity activity){  
        this.views = views;  
        this.activity = activity;
    }  
    
	@Override
	public int getCount() {
		if (views != null) {
			return views.size();
		}
		return 0;
	}
	
	//销毁arg1位置的界面  
    @Override  
    public void destroyItem(View arg0, int arg1, Object arg2) {  
        ((ViewPager) arg0).removeView(views.get(arg1));       
    }  
  
    @Override  
    public void finishUpdate(View arg0) {  
          
    }  
  //初始化arg1位置的界面  
    @Override  
    public Object instantiateItem(View arg0, int arg1) {  
          
        ((ViewPager) arg0).addView(views.get(arg1), 0);  
        if (arg1 == views.size() - 1) {
            ImageView mStartWeiboImageButton = (ImageView) arg0
                    .findViewById(R.id.btn_start);
            mStartWeiboImageButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 设置已经引导
                    updateCodeVersion();
                    goHome();

                }

            });
        }
        return views.get(arg1);  
    }  
  
    protected void goHome() {
    	Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
        activity.finish();		
	}

	protected void updateCodeVersion() {
    	PackageManager pm = activity.getPackageManager();
		Application app = activity.getApplication();
		PackageInfo pi = null;
		try {
			pi = pm.getPackageInfo(app.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		SharedPreferencesHelper.setInt(SharedPreferencesHelper.Field.CODE_VERSION, pi.versionCode);
    }

	//判断是否由对象生成界面  
    @Override  
    public boolean isViewFromObject(View arg0, Object arg1) {  
        return (arg0 == arg1);  
    }  
  
    @Override  
    public void restoreState(Parcelable arg0, ClassLoader arg1) {  
          
    }  
  
    @Override  
    public Parcelable saveState() {  
        return null;  
    }  
  
    @Override  
    public void startUpdate(View arg0) {  
          
    }  
}
